using System.Collections;
using DG.Tweening;
using UnityEngine;

public class RollingBall : MonoBehaviour
{
	public float speed = 10f;

	public float destroyYLimit = -100f;

	[HideInInspector]
	public Vector3 startPosition;

	private Vector3 startScale;

	private bool isAlive;

	private Tweener moveTween;

	private Vector3 currentPosition;

	private void Start()
	{
		EventManager.WorldResetEvent += OnWorldReset;
		LevelController.LevelDestroyEvent += OnLevelDestroy;
	}

	private void OnDestroy()
	{
		EventManager.WorldResetEvent -= OnWorldReset;
		LevelController.LevelDestroyEvent -= OnLevelDestroy;
	}

	private void OnWorldReset()
	{
		isAlive = false;
		base.GetComponent<Renderer>().enabled = false;
		if (moveTween != null)
		{
			moveTween.Kill();
			moveTween = null;
		}
		Object.Destroy(base.gameObject);
	}

	private void OnLevelDestroy(Transform levelTransform)
	{
		if (moveTween != null)
		{
			moveTween.Kill();
			moveTween = null;
		}
	}

	public void Shot(Vector3 startPos)
	{
		if (!isAlive)
		{
			startScale = base.transform.localScale;
			startPosition = startPos;
			Vector3 endPosition = startPos + base.transform.TransformDirection(Vector3.forward * 1.1f);
			currentPosition = startPosition;
			base.transform.position = startPosition;
			base.GetComponent<Rigidbody>().isKinematic = true;
			base.GetComponent<Rigidbody>().MovePosition(startPosition);
			base.GetComponent<Rigidbody>().maxAngularVelocity = 20f;
			base.GetComponent<Renderer>().enabled = true;
			StartCoroutine(ShotNextFrame(endPosition));
		}
	}

	private void OnMoveTweenUpdate()
	{
		base.transform.position = currentPosition;
	}

	private IEnumerator ShotNextFrame(Vector3 endPosition)
	{
		yield return null;
		yield return new WaitForEndOfFrame();
		if (base.transform != null)
		{
			moveTween = DOTween.To(() => currentPosition, delegate(Vector3 x)
			{
				currentPosition = x;
			}, endPosition, 0.3f).SetEase(Ease.InSine).OnUpdate(OnMoveTweenUpdate)
				.OnComplete(OnMoveTweenComplete);
		}
	}

	private void OnMoveTweenComplete()
	{
		base.GetComponent<Renderer>().castShadows = true;
		base.GetComponent<Rigidbody>().isKinematic = false;
		base.GetComponent<Rigidbody>().AddForce(base.transform.TransformDirection(Vector3.forward) * 2f, ForceMode.VelocityChange);
	}

	private void Update()
	{
		if (base.transform.position.y - startPosition.y < destroyYLimit)
		{
			Object.Destroy(base.gameObject);
		}
		if (base.transform.position.y - startPosition.y < destroyYLimit * 0.75f)
		{
			base.GetComponent<Collider>().enabled = false;
			float num = (destroyYLimit - (base.transform.position.y - startPosition.y)) / (destroyYLimit * 0.25f);
			base.transform.localScale = startScale * num;
		}
	}
}
